//
//  BaseViewController.m
//  CommunityCircle
//
//  Created by liuchao on 16/1/11.
//  Copyright © 2016年 ssyx. All rights reserved.
//

#import "BaseViewController.h"
#import "HeadTopView.h"





@interface BaseViewController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIButton    *leftBtn;
@property (nonatomic, strong) UIView      *circleView;
@property (nonatomic, strong) UILabel     *circleLabel;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) HeadTopView *headView;

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - init
- (void)setupConfigureView { }


#pragma mark - head view
- (void)loadHeadView {
    [self loadHeadView:nil];
}
- (void)loadHeadView:(NSString  *)title {
    [self loadHeadView:title showBackBtn:YES];
}
- (void)loadHeadView:(NSString *)title showBackBtn:(BOOL)showleft {
    [self loadHeadView:title showLeftBtn:showleft leftImageName:@"返回" leftTitle:nil]; // 返回 //左箭头-2

}
- (void)loadHeadView:(NSString *)title
         showLeftBtn:(BOOL)showleft
       leftImageName:(NSString *)leftImageName
           leftTitle:(NSString *)leftTitle {
    [self loadHeadView:title showLeftBtn:showleft showRightBtn:NO leftImageName:leftImageName rightImageName:nil leftTitle:leftTitle rightTitle:nil];
}

- (void)loadHeadView:(NSString *)title
         addRightBtn:(BOOL)showRight
      rightImageName:(NSString *)rightImageName
          rightTitle:(NSString *)rightTitle {
    [self loadHeadView:title showLeftBtn:YES showRightBtn:showRight leftImageName:@"返回" rightImageName:rightImageName leftTitle:nil rightTitle:rightTitle]; // 返回 //左箭头-2
}
- (void)loadHeadView:(NSString *)title
        showRightBtn:(BOOL)showRight
      rightImageName:(NSString *)rightImageName
          rightTitle:(NSString *)rightTitle {
    [self loadHeadView:title showLeftBtn:NO showRightBtn:showRight leftImageName:nil rightImageName:rightImageName leftTitle:nil rightTitle:rightTitle];
}

- (void)loadHeadView:(NSString *)title
         showLeftBtn:(BOOL)showleft
        showRightBtn:(BOOL)showRight
       leftImageName:(NSString *)leftImageName
      rightImageName:(NSString *)rightImageName
           leftTitle:(NSString *)leftTitle
          rightTitle:(NSString *)rightTitle {
    
    self.headView = [[HeadTopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kNavigationBarHeight)];
    self.headView.text = title ? : self.title;
    self.headView.showLeft = showleft;
    self.headView.showRight = showRight;
    
    self.headView.leftImageName = leftImageName;
    self.headView.leftTitle = leftTitle;
    
    self.headView.rightImageName = rightImageName;
    self.headView.rightTitle = rightTitle;
    
    @weakify(self)
    [[self.headView getSignalWithDictionary:@{@"action" : @"left"}] subscribeNext:^(id x) {
        @strongify(self)
        [self headLeftAction];
    }];
    [[self.headView getSignalWithDictionary:@{@"action" : @"right"}] subscribeNext:^(id x) {
        @strongify(self)
        [self headRightAction];
    }];
    [self.view addSubview:self.headView];
}
- (void)setHNavigationTitle:(NSString  *)title{
    self.headView.text = title;
}
- (void)headLeftAction {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)headRightAction { }
- (void)hiddenLeftButton{
    [self.leftBtn setHidden:YES];
}

#pragma mark - hud
- (void)showCircleView:(BOOL)show {
    [self showCircleView:show message:nil];
}

- (void)showCircleView:(BOOL)show message:(NSString *)message {
    self.circleView.hidden = !show;
    self.circleLabel.text = message;
    
    if ([message hasPrefix:@"暂无数据"] || [message hasPrefix:@"获取失败"]) {
        [self.imageView.layer removeAllAnimations];
        self.imageView.image = [UIImage imageNamed:@"NetPlaceHolder"];
    }
}

- (void)showCircleView:(BOOL)show message:(NSString *)message place:(BOOL)place {
    self.circleView.hidden = !show;
    self.circleLabel.text = message;
    
    if (place == YES) {
        [self.imageView.layer removeAllAnimations];
        self.imageView.image = [UIImage imageNamed:@"NetPlaceHolder"];
    }
}

- (void)showLoadViewTo:(UIView *)view hidden:(BOOL)hidden showPlaceholder:(BOOL)place message:(NSString *)message {
    UIView *backView = view;
    if (view == nil) {
        backView = [UIApplication sharedApplication].keyWindow;
    }
    
    if (self.circleView.superview != view) {
        [self.circleView removeFromSuperview];
        [backView addSubview:self.circleView];
    }
    
    self.circleView.hidden = hidden;
    self.circleLabel.text = message;
    if (place == YES) {
        [self.imageView.layer removeAllAnimations];
        self.imageView.image = [UIImage imageNamed:IMG_EmptyDefault];
    } else {
        NSArray *animations = [self.imageView.layer animationKeys];
        __block BOOL isexist = NO;
        [animations enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([key isEqualToString:@"CircleImageViewKey"]) {
                isexist = YES;
                *stop = YES;
            }
        }];
        
        if (isexist == NO) {
            CAAnimation *animation = [self dzn_imageAnimation];
            if (animation) {
                [self.imageView.layer addAnimation:animation forKey:@"CircleImageViewKey"];
            }
        }
        self.imageView.image = [UIImage imageNamed:@"loading_imgBlue"];
    }
}


#pragma mark - viewModel

- (void)bindViewModel { }

- (void)didViewModelNoMsgWithCompletionBlock:(void (^)(id receive))completionBlock {
    if (!self.viewModel) return;
    
    [self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(id receive) {
        if (completionBlock) completionBlock(receive);
    }];
}

- (void)didViewModelWithCompletionBlock:(void (^)(id receive))completionBlock {
    [self didViewModelWithCompletionBlock:completionBlock showMsg:NO delayBlock:nil];
}

- (void)didViewModelWithDelayBlock:(void (^)(id receive))delayBlock {
    [self didViewModelWithCompletionBlock:nil showMsg:YES delayBlock:delayBlock];
}

- (void)didViewModelWithCompletionBlock:(void (^)(id receive))completionBlock showMsg:(BOOL)showMsg delayBlock:(void (^)(id receive))delayBlock {
    if (!self.viewModel) return;
    
    @weakify(self)
    [self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(id receive) {
        @strongify(self)
        
        if (completionBlock) completionBlock(receive);
        
        if (showMsg == YES) {
            [MBProgressHUD showTextOnly:self.view message:self.viewModel.msg delay:1.6 completionBlock: ^ {
                if (delayBlock) delayBlock(receive);
            }];
        } else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    }];
    
    [self.viewModel.command.executing subscribeNext:^(NSNumber *executing) {
        @strongify(self)
        if (executing.boolValue) {      // 正在加载
            [MBProgressHUD showLoadingImageToView:self.view];
        }
    }];
    
    [self.viewModel.command.errors subscribeNext:^(NSError *error) {
        @strongify(self)
        [MBProgressHUD showTextOnly:self.view message:error.domain];
    }];
}

- (void)didViewModelType:(NSUInteger)type delay:(CGFloat)delay completionBlock:(void (^)(id receive))completionBlock {
    if (!self.viewModel) return;
    
    @weakify(self)
    [self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(id receive) {
        @strongify(self)
        
        if (type == 0) {        // 边展示，边执行
            [MBProgressHUD showTextOnly:self.view message:self.viewModel.msg delay:delay];
            completionBlock(receive);
        } else {                // 展示完后执行
            [MBProgressHUD showTextOnly:self.view message:self.viewModel.msg delay:1.6 completionBlock: ^ {
                completionBlock(receive);
            }];
        }
    }];
    
    [self.viewModel.command.executing subscribeNext:^(NSNumber *executing) {
        @strongify(self)
        if (executing.boolValue) {      // 正在加载
            [MBProgressHUD showLoadingImageToView:self.view];
        }
    }];
    
    [self.viewModel.command.errors subscribeNext:^(NSError *error) {
        @strongify(self)
        [MBProgressHUD showTextOnly:self.view message:error.domain];
    }];
}


#pragma mark - getter

- (UILabel *)circleLabel {
    if (!_circleLabel) {
        _circleLabel = [UILabel new];
        _circleLabel.font = [UIFont systemFontOfSize:17.0];
        _circleLabel.textColor = [UIColor grayColor];
        _circleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _circleLabel;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [UIImageView new];
        _imageView.image = [UIImage imageNamed:@"loading_imgBlue"];
        CAAnimation *animation = [self dzn_imageAnimation];
        if (animation) {
            [_imageView.layer addAnimation:animation forKey:@"CircleImageViewKey"];
        }
    }
    return _imageView;
}

- (UIView *)circleView {
    if (!_circleView) {
        _circleView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - kNavigationBarHeight)];
//        _circleView.backgroundColor = [UIColor redColor];
        [_circleView addSubview:self.imageView];
        self.imageView.frame = CGRectMake(SCREEN_WIDTH / 2 - 40, SCREEN_HEIGHT / 3 - 72, 80, 80);
        
        [_circleView addSubview:self.circleLabel];
        self.circleLabel.frame = CGRectMake(0, CGRectGetMaxY(self.imageView.frame), SCREEN_WIDTH, 40);
        
        [self.view addSubview:_circleView];
    }
    return _circleView;
}

- (CAAnimation *) dzn_imageAnimation {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;
    return animation;
}

- (MBProgressHUD *)HUD {
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        
        _HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading_imgBlue"]];
        CAAnimation *animation = [self dzn_imageAnimation];
        if (animation) {
            [_HUD.customView.layer addAnimation:animation forKey:@"CircleImageViewKey"];
        }
        
        // Set custom view mode
        _HUD.mode = MBProgressHUDModeCustomView;
        _HUD.bezelView.alpha = 0.0;
        _HUD.removeFromSuperViewOnHide = NO;
        //        [self.view addSubview:_HUD];
    }
    return _HUD;
}

- (BOOL)shouldAutorotate {
    return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait;
}


@end
